#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project ：Employment_class 
@File    ：06_TFTP客户端.py
@IDE     ：PyCharm 
@Author  ：XiaoDengYa
@Date    ：2021/7/5/005 15:11 
"""

import struct
from socket import *

udpSocket = socket(AF_INET, SOCK_DGRAM)

filename = input("请输入需要下载的文件：")

buf = cmd_buf = struct.pack("!H%dsb5sb" % len(filename), 1, filename.encode("utf-8"), 0, "octet".encode("utf-8"), 0)

sendAddr = ("192.168.10.114", 69)

udpSocket.sendto(buf, sendAddr)

p_num = 0
recvFile = ""

while True:
    recvData, recvAddr = udpSocket.recvfrom(1024)

    recvDataLen = len(recvData)

    cmdTuple = struct.unpack("!HH", recvData[:4])

    cmd = cmdTuple[0]
    currentPackNum = cmdTuple[1]

    if cmd == 3:
        if currentPackNum == 1:
            recvFile = open(filename, "a+")

        if p_num + 1 == currentPackNum:
            recvFile.write(recvData[4:])
            p_num += 1
            print("%d次接收到的数据" % p_num)

            ackBuf = struct.pack("!HH", 4, p_num)

            udpSocket.sendto(ackBuf, recvAddr)

        if recvDataLen < 516:
            recvFile.close()
            print("下载成功！")
            break
    elif cmd == 5:
        print("请求报错！！")
        break

udpSocket.close()
